/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hextd.server;

import com.usoog.tdcore.gameloop.GameLoopManager;
import com.usoog.tdcore.gamestate.GameState;
import com.usoog.tdcore.map.MapInfo;
import com.usoog.tdcore.message.MessageReplay;
import hextd.Constants.settingKey;
import hextd.core.GameManagerImplementation;
import hextd.core.MapLoaderServer;
import java.io.BufferedReader;
import java.io.StringReader;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 *
 * @author hylke
 */
public class ReplayLogChecker {

	private List<MessageReplay> logsToCheck;
	private Map<Integer, ServerUser> playersByUserId;
	private Timer checkTimer;
	private TimerTask checkTask, regTask;
	private URL spPostUrl;
	private URL mpPostUrl;
	private MapLoaderServer mapLoader;
	//
	public static final String playerUpdateRegExp = "([0-9-]+),([0-9-]+),([0-9-]+)";
	public static Pattern playerUpdatePattern = Pattern.compile(playerUpdateRegExp);

	public ReplayLogChecker(Map<Integer, ServerUser> playersByUserId, List<MessageReplay> logsToCheck, URL spPostUrl, URL mpPostUrl, MapLoaderServer mapLoader, Timer timer) {
		checkTimer = timer;
		this.playersByUserId = playersByUserId;
		this.logsToCheck = logsToCheck;
		this.spPostUrl = spPostUrl;
		this.mpPostUrl = mpPostUrl;
		this.mapLoader = mapLoader;
	}

	public void runCheck() {
		while (logsToCheck.size() > 0) {
			checkLog(logsToCheck.remove(0));
		}
	}

	private void checkLog(MessageReplay mrl) {
		Map<String, String> options = mrl.getOptions();
		String selectedMap = options.get(settingKey.selectedMap.name());
		int mapId = Integer.parseInt(selectedMap);
		if (mapId <= 0) {
			return;
		}
		GameManagerImplementation gm = new GameManagerImplementation();
		GameState gs = gm.getGameState();
		GameLoopManager glm = gm.getGameLoopManager();
		gm.setMapLoader(mapLoader);
		MapInfo map = mapLoader.getMap(mapId);
		map.getMapData().loadIntoGameState(gs);
		int lastTick = gm.loadLog(new BufferedReader(new StringReader(mrl.getReplay())));

		gs.setGamePhase("checking");
		glm.setRunning(true);
		glm.run();

		// TODO: Handle results of the game...


	}

	public synchronized void startCheckTimer() {
		if (checkTimer == null) {
			checkTimer = new Timer("ReplayCheckTimer", true);
		}
		if (checkTask == null) {
			checkTask = new TimerTask() {

				@Override
				public void run() {
					runCheck();
				}
			};
			checkTimer.schedule(checkTask, 100, 1000);
		}
	}

	public void stopCheckTimer() {
		this.checkTask.cancel();
		this.checkTask = null;
	}
}
